﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SQLite;
using System.Data;

namespace PTCScheduler
{
    /// <summary>
    /// Interaction logic for ViewByTeacher.xaml
    /// </summary>
    public partial class ViewBy_TeacherPage : Page, ScheduleReport
    {
        //SQlite connection for student page
        private SQLiteConnection conn;

        //SQlite data adapter for student page
        private SQLiteDataAdapter da;

        //SQLite connection string
        private String connString = SystemQueries.dbConnString();

        //Empty Constructor
        public ViewBy_TeacherPage()
        {
            //Initalize page
            InitializeComponent();

            //Bind teacher names to combobox.
            BindComboBox();
        }

        //Connect to the database.
        public void dbConn()
        {
            //Create connection.
            conn = new SQLiteConnection(connString);

            //Open connection
            conn.Open();
        }

        //Query the results and fill the corresponding datagridview control.
        public void queryResults()
        {
            //Hide teacher warning label by default.
            teacherwarninglbl.Visibility = Visibility.Hidden;

            try
            {
                //Retrieve text from the combobox.
                String fullTeacherName = teachercomboBox.Text;

                //Retrieve index of comma to find various parts of name.
                int commaIndex = fullTeacherName.IndexOf(',');

                //Throw exception if comma index is not found and prompt user
                //to input a valid name.
                if (commaIndex == -1)
                {
                    throw new Exception();
                }

                //If full teacher name is 
                //Retrieve first, middle, and last name from the full teacher name string.
                String fname = fullTeacherName.Substring(commaIndex + 2);
                String lname = fullTeacherName.Substring(0, commaIndex);

                //Retrieve the teacher query string from the SystemQueries class and set the
                //teacher first and last name to the desired teacher name in teachercombobox.
                String sql = SystemQueries.teacherQueryString(fname, lname);

                //Create dataset to fill with the results of the query. 
                DataSet ds = new DataSet(); //System.Data assembly

                //User SQLiteDataAdapter to retrieve results. 
                da = new SQLiteDataAdapter(sql, connString);

                //Fill the dataset with the results. 
                da.Fill(ds);

                //If there are no records then prompt user that there are no scheduled
                //conferences for teacher. Otherwise just display records. 
                if (ds.Tables[0].Rows.Count == 0)
                {
                    teachernoconferenceslbl.Visibility = Visibility.Visible;
                }
                else
                {
                    teachernoconferenceslbl.Visibility = Visibility.Hidden;
                }
                //Format date and time.
                dtFormat(ds);

                //Display results in datagrid view. 
                dataGridTeacher.ItemsSource = ds.Tables[0].DefaultView;

            }
            catch (Exception)
            {
                //Prompt user to enter a valid name.
                teacherwarninglbl.Visibility = Visibility.Visible;
            }
            finally
            {
                //Close and dispose db connection.
                conn.Close();
                conn.Dispose();
            }
        }

        //Method to format the date and time column
        private void dtFormat(DataSet ds)
        {
            //Iterate through each row and format accordinly
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                //Create date time object
                DateTime dt = DateTime.Parse(row["Time"].ToString());
                //Set column equal to desired date pattern.
                row["Time"] = dt.ToString("hh:mm tt");
            }
        }

        //Method to hide all labels.
        private void HideAllLabels()
        {
            teacherwarninglbl.Visibility = Visibility.Visible;
            teachernoconferenceslbl.Visibility = Visibility.Visible;
        }

        //Clear textbox and refocus on textbox.
        private void ClearForm()
        {
            //Clear.
            teachercomboBox.Text = "";
            //Reset Focus.
            teachercomboBox.Focus();
        }

        //Method to bind data to combox box. Queries teacher names and binds them to combo box.
        private void BindComboBox()
        {
            //Open database connection.
            dbConn();

            //Retrieve the teacher query string from the SystemQueries class and set the
            //teacher combobox contents to teacher names.
            String sql = SystemQueries.teacherComboBox();

            //Create dataset to fill with the results of the query. 
            DataSet ds = new DataSet(); //System.Data assembly

            //User SQLiteDataAdapter to retrieve results. 
            SQLiteDataAdapter da2 = new SQLiteDataAdapter(sql, connString);

            //Fill the dataset with the results. 
            da2.Fill(ds);

            //Set combobox data source to query results.
            teachercomboBox.ItemsSource = ds.Tables[0].DefaultView;

            //Ensure the item source knows which member of the table to search.
            teachercomboBox.DisplayMemberPath = "Teacher";

            //Close connection.
            conn.Close();
        }

        //Fire off the action when search button is clicked.
        private void searchbyteacherbtn_Click(object sender, RoutedEventArgs e)
        {
            //Open database connection.
            dbConn();

            //Query the results and fill datagridview.
            queryResults();
        }

        //Code to get drop down portion to drop down when mouse hovers over combobox.
        private void teachercomboBox_MouseEnter(object sender, MouseEventArgs e)
        {
            teachercomboBox.IsDropDownOpen = true;
        }

        //Handles Export Button Click Event.
        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            //Check to ensure data is available in datagrid.
            if (dataGridTeacher.Items.Count > 0)
            {
                //Create new instance of CSVExport object which invokes the export to CSV method
                //to export data to excel worksheet.
                new CSVExport(dataGridTeacher);
            }
        }

        //Handles Print Button Click Event.
        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            //Create new instance of the PrintDataGrid object which invokes the print feature
            //that prints contents of datagrid.
            new PrintDataGrid(dataGridTeacher);
        }
    }
}
